import java.awt.*;

import javax.swing.*;
import javax.swing.border.*;

import java.awt.event.*;
import java.io.*;

public class SimpleTextEditor extends JFrame implements ItemListener {

	JButton open, save, saveAs, close, about;
	JTextArea text;
	JFileChooser fc;
	JToolBar toolBar;

	JMenuBar	menu;
	JMenu		fileMenu, formulaeMenu, tableMenu, viewMenu, helpMenu,
				newFileMenu;
	
	JMenuItem	openMenuItem, newTextFileItem, newCsvFileItem,
				saveMenuItem, saveAsMenuItem, saveAllMenuItem,
				closeMenuItem, closeAllMenuItem,
				aboutMenuItem,
				cutMenuItem, copyMenuItem, pasteMenuItem;
				
	
	Action		openAction, newTextFileAction, newCsvFileAction,
				saveAction, saveAsAction, saveAllAction,
				closeAction, closeAllAction,
				aboutAction;
	
	JCheckBoxMenuItem textMenuItem;
	JPopupMenu popupMenu;
	
	
	boolean showtxt = false;
	File oldFile = null;

	public SimpleTextEditor () {
		super("Simple Text Editor");
		fc = new JFileChooser();

		
		//action
		openAction = new OpenAction( "Open", 
									 new ImageIcon("open.gif"), 
								 	 KeyEvent.VK_O);
		
		newTextFileAction = new NewTextFileAction( "New text file",
													null,
													KeyEvent.VK_O);
		
		newCsvFileAction = new NewCsvFileAction( "New csv file",
												  null,
												  KeyEvent.VK_O);
		
		saveAction = new SaveAction( "Save", 
									 new ImageIcon("save.gif"), 
									 KeyEvent.VK_S);
		
		saveAsAction = new SaveAsAction( "Save As",
										 new ImageIcon("saveAs.gif"),
										 KeyEvent.VK_A);
		
		saveAllAction = new SaveAllAction( "Save All",
				 						   null,
				 						   KeyEvent.VK_L);
		
		closeAction = new CloseAction( "Close", 
									   new ImageIcon("close.gif"),
									   KeyEvent.VK_C);
		
		closeAllAction = new CloseAction( "Close all", 
				   						   null,
				   						   0);
		
		aboutAction = new AboutAction( "About", 
									   new ImageIcon("about.gif"),
									   KeyEvent.VK_H);

		//new menu
		menu = new JMenuBar();
		
		fileMenu = new JMenu("File");
		fileMenu.setMnemonic(KeyEvent.VK_F);
		
		formulaeMenu = new JMenu("Formulae");
		formulaeMenu.setMnemonic(KeyEvent.VK_M);
		
		tableMenu = new JMenu("Table");
		tableMenu.setMnemonic(KeyEvent.VK_T);
		
		viewMenu = new JMenu("View");
		viewMenu.setMnemonic(KeyEvent.VK_V);
		
		helpMenu = new JMenu("Help");
		helpMenu.setMnemonic(KeyEvent.VK_H);
		
		newFileMenu = new JMenu("New File");
		
		menu.add(fileMenu);
		menu.add(formulaeMenu);
		menu.add(tableMenu);
		menu.add(viewMenu);
		menu.add(helpMenu);
		
		
		//new menu item
		openMenuItem = new JMenuItem(openAction);
		openMenuItem.setIcon(null);
		saveMenuItem = new JMenuItem(saveAction);
		saveMenuItem.setIcon(null);
		saveAsMenuItem = new JMenuItem(saveAsAction);
		saveAsMenuItem.setIcon(null);
		saveAllMenuItem = new JMenuItem(saveAllAction);
		saveAllMenuItem.setIcon(null);
		closeMenuItem = new JMenuItem(closeAction);
		closeMenuItem.setIcon(null);
		closeAllMenuItem = new JMenuItem(closeAllAction);
		closeAllMenuItem.setIcon(null);
		aboutMenuItem = new JMenuItem(aboutAction);
		aboutMenuItem.setIcon(null);
		newTextFileItem = new JMenuItem("New text file");
		newCsvFileItem = new JMenuItem("New csv file");
		
		
		
		newFileMenu.add(newTextFileItem);
		newFileMenu.add(newCsvFileItem);
		
		fileMenu.add(newFileMenu);
		fileMenu.add(openMenuItem);
		fileMenu.addSeparator();
		fileMenu.add(saveMenuItem);
		fileMenu.add(saveAsMenuItem);
		fileMenu.add(saveAllMenuItem);
		fileMenu.addSeparator();
		fileMenu.add(closeMenuItem);
		fileMenu.add(closeAllMenuItem);
		
		text = new JTextArea();
		add(new JScrollPane(text));
		
		cutMenuItem = new JMenuItem("Cut");
		cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
		copyMenuItem = new JMenuItem("Copy");
		copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
		pasteMenuItem = new JMenuItem("Paste");
		pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
		
		popupMenu = new JPopupMenu();
		popupMenu.add(cutMenuItem);
		popupMenu.add(copyMenuItem);
		popupMenu.add(pasteMenuItem);
		
		cutMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				text.cut();
			}
		});
		copyMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				text.copy();
			}
		});
		pasteMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				text.paste();
			}
		});
		text.addMouseListener(new MouseAdapter() {
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					popupMenu.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		});
		
		
		aboutMenuItem = new JMenuItem(aboutAction);
		helpMenu.add(aboutMenuItem);

		toolBar = new JToolBar();
		open = new JButton(openAction);
		 if (open.getIcon() != null) {
			 open.setText(""); //an icon-only button
	        }
		save = new JButton(saveAction);
		 if (save.getIcon() != null) {
			 save.setText(""); //an icon-only button
	        }
		

		toolBar.add(open);
		add(toolBar, BorderLayout.NORTH);
		toolBar.add(save);
		add(toolBar, BorderLayout.NORTH);
		toolBar.setFloatable(true);


		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(600, 480);
		setJMenuBar(menu);
	}
	
		
	

	public void openFile() {
		int state = fc.showOpenDialog(null);
        oldFile = fc.getSelectedFile();
        if(oldFile != null && state == JFileChooser.APPROVE_OPTION) {
        	String content = reader(oldFile);
    		text.setText(content);
        }
	}
	public String reader(File file) {
		String content = "";
    	String line;
		String fileName = file.getPath();
		try{
			BufferedReader in = new BufferedReader(new FileReader(fileName)); 
			line = in.readLine();
			while(line != null) {
				content += line + "\n";
			   line = in.readLine();
		   }
		   in.close();
		}catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}
	public void writer(File file, String content) {
		try {
			BufferedWriter outFile = new BufferedWriter(new FileWriter(file));
			outFile.write(content);
			outFile.flush();
			outFile.close();
		}catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	public void itemStateChanged(ItemEvent e) {
		showtxt = textMenuItem.isSelected();
		showText(textMenuItem.isSelected());
	}
	public void showText(boolean showtxt) {
		    Component c[] = toolBar.getComponents();
		    for(int i=0;i<c.length;i++) 
		    	if (c[i] instanceof JButton) {
					JButton button = (JButton) c[i];
					if (showtxt)
						button.setText((String) button.getAction().getValue(
								Action.NAME));
					else
						button.setText(null);
		    	}
	}
	public static void main(String args[]) {
		SimpleTextEditor app = new SimpleTextEditor();
		app.setVisible(true);
	}
	//action class 
	class OpenAction extends AbstractAction {
		public OpenAction(String text, ImageIcon icon, int mnemonic) {
			super(text, icon);
			putValue(MNEMONIC_KEY, mnemonic);
			putValue(SHORT_DESCRIPTION, text);
		}
		public void actionPerformed(ActionEvent e) {
			int state = fc.showOpenDialog(null);
	        oldFile = fc.getSelectedFile();
	        if(oldFile != null && state == JFileChooser.APPROVE_OPTION) {
	        	String content = reader(oldFile);
	    		text.setText(content);
	        }
		}
	}
	
	class NewTextFileAction extends AbstractAction {
		public NewTextFileAction(String text, ImageIcon icon, int mnemonic) {
			super(text, icon);
			putValue(MNEMONIC_KEY, mnemonic);
			putValue(SHORT_DESCRIPTION, text);
		}
		public void actionPerformed(ActionEvent e) {
			
		}
	}
	class NewCsvFileAction extends AbstractAction {
		public NewCsvFileAction(String text, ImageIcon icon, int mnemonic) {
			super(text, icon);
			putValue(MNEMONIC_KEY, mnemonic);
			putValue(SHORT_DESCRIPTION, text);
		}
		public void actionPerformed(ActionEvent e) {
			
		}
	}
	class SaveAction extends AbstractAction {
		public SaveAction(String text, ImageIcon icon, int mnemonic) {
			super(text, icon);
			putValue(MNEMONIC_KEY, mnemonic);
			putValue(SHORT_DESCRIPTION, text);
		}
		public void actionPerformed(ActionEvent e) {
			if (oldFile != null) {
				String content = text.getText();
				writer(oldFile,content);
				}
				else {
					int state = fc.showSaveDialog (null);
					File file = fc.getSelectedFile ();
					if (file != null && state == JFileChooser.APPROVE_OPTION) {
						if (file.exists()) {
							int response = JOptionPane.
			            		 			showConfirmDialog (
			            		 					null,
			            		 					"Overwrite existing file?","Confirm Overwrite",
			            		 					JOptionPane.OK_CANCEL_OPTION,
			            		 					JOptionPane.QUESTION_MESSAGE);
							if (response == JOptionPane.CANCEL_OPTION) {
								return;
							}
						}
					}
				} 
		}
	}
	class SaveAsAction extends AbstractAction {
		public SaveAsAction(String text, ImageIcon icon, int mnemonic) {
			super(text, icon);
			putValue(MNEMONIC_KEY, mnemonic);
			putValue(SHORT_DESCRIPTION, text);
		}
		public void actionPerformed(ActionEvent e) {
			int state = fc.showSaveDialog (null);
			File file = fc.getSelectedFile ();
			if (file != null && state == JFileChooser.APPROVE_OPTION) {
				if (file.exists()) {
					int response = JOptionPane.
	            		 			showConfirmDialog (
	            		 					null,
	            		 					"Overwrite existing file?",
	            		 					"Confirm Overwrite",
	            		 					JOptionPane.OK_CANCEL_OPTION,
	            		 					JOptionPane.QUESTION_MESSAGE);
					if (response == JOptionPane.CANCEL_OPTION) {
						return;
					}
				}
				String content = text.getText();
				writer(file, content);
			}
		}
	}
	class SaveAllAction extends AbstractAction {
		public SaveAllAction(String text, ImageIcon icon, int mnemonic) {
			super(text, icon);
			putValue(MNEMONIC_KEY, mnemonic);
			putValue(SHORT_DESCRIPTION, text);
		}
		public void actionPerformed(ActionEvent e) {
			int state = fc.showSaveDialog (null);
			File file = fc.getSelectedFile ();
			if (file != null && state == JFileChooser.APPROVE_OPTION) {
				if (file.exists()) {
					int response = JOptionPane.
	            		 			showConfirmDialog (
	            		 					null,
	            		 					"Overwrite existing file?",
	            		 					"Confirm Overwrite",
	            		 					JOptionPane.OK_CANCEL_OPTION,
	            		 					JOptionPane.QUESTION_MESSAGE);
					if (response == JOptionPane.CANCEL_OPTION) {
						return;
					}
				}
				String content = text.getText();
				writer(file, content);
			}
		}
	}
	class CloseAction extends AbstractAction {
		public CloseAction(String text, ImageIcon icon, int mnemonic) {
			super(text, icon);
			putValue(MNEMONIC_KEY, mnemonic);
			putValue(SHORT_DESCRIPTION, text);
		}
		public void actionPerformed(ActionEvent e) {
			oldFile = null;
			text.setText("");
		}
	}
	class CloseAllAction extends AbstractAction {
		public CloseAllAction(String text, ImageIcon icon, int mnemonic) {
			super(text, icon);
			putValue(MNEMONIC_KEY, mnemonic);
			putValue(SHORT_DESCRIPTION, text);
		}
		public void actionPerformed(ActionEvent e) {
			oldFile = null;
			text.setText("");
		}
	}
	class AboutAction extends AbstractAction {
		AboutBox dialog;
		public AboutAction(String text, ImageIcon icon, int mnemonic) {
			super(text, icon);
			putValue(MNEMONIC_KEY, mnemonic);
			putValue(SHORT_DESCRIPTION, text);
		}
		public void actionPerformed(ActionEvent e) {
			dialog = new AboutBox(null);
			dialog.setVisible(true);
		}
	}
	class AboutBox extends JDialog {
		  public AboutBox(Frame owner) {
		    super(owner, "About Swing Menu", true);

		    JLabel lbl = new JLabel(new ImageIcon("about.gif"));
		    JPanel p = new JPanel();
		    Border b1 = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
		    Border b2 = BorderFactory.createEmptyBorder(5, 5, 5, 5);
		    lbl.setBorder(BorderFactory.createCompoundBorder(b1, b2));
		    p.add(lbl);
		    getContentPane().add(p, BorderLayout.WEST);

		    String message = "Swing Simple Text Editor\n"+
		      "Copyright (c) Ian Foley, 2000";
		    JTextArea txt = new JTextArea(message);
		    txt.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
		    txt.setFont(new Font("Helvetica", Font.BOLD, 12));
		    txt.setEditable(false);
		    txt.setBackground(getBackground());
		    p = new JPanel();
		    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
		    p.add(txt);

		    message = "This program illustrates the use of\n"+
		      "many Swing features";
		    txt = new JTextArea(message);
		    txt.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
		    txt.setFont(new Font("Arial", Font.PLAIN, 12));
		    txt.setEditable(false);
		    txt.setBackground(getBackground());
		    p.add(txt);

		    getContentPane().add(p, BorderLayout.CENTER);

		    JButton btOK = new JButton("OK");
		    ActionListener lst = new ActionListener()
		    {
		      public void actionPerformed(ActionEvent e)
		      {
		        setVisible(false);
		      }
		    };
		    btOK.addActionListener(lst);
		    p = new JPanel();
		    p.add(btOK);
		    getContentPane().add(p, BorderLayout.SOUTH);

		    pack();
		    setResizable(false);
		  }
		}
}